﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    
    class NetworkListener
    {
        private int g_Listening_Port;
        private UdpClient g_Udp_Listener;
        private IPEndPoint g_IPE_Point;

        /// <summary>
        /// Init the udp listener
        /// </summary>
        /// <param name="p_Listening_Port">
        /// the udp listening port that will be used for this connection
        /// </param>
        public NetworkListener(int p_Listening_Port)
        {
            this.g_Listening_Port = p_Listening_Port;
            this.g_Udp_Listener = new UdpClient(p_Listening_Port);
            this.g_IPE_Point = new IPEndPoint(IPAddress.Any, p_Listening_Port);
        }

        public void receiveData()
        {
            string l_Received_Data;
            byte[] l_Received_data_array;
            try
            {
                while (true)
                {
                    Console.WriteLine("Waiting for data");

                    //Receive the data from client
                    l_Received_data_array = this.g_Udp_Listener.Receive(ref this.g_IPE_Point);
                    Console.WriteLine("Received a broadcast from {0}", this.g_IPE_Point.ToString());

                    //encode the data in the ASCII
                    l_Received_Data = Encoding.ASCII.GetString(l_Received_data_array, 0, l_Received_data_array.Length);
                    Console.WriteLine("data follows \n{0}\n\n", l_Received_Data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            this.g_Udp_Listener.Close();

        }
    }
}
